import html2canvas from 'html2canvas'
import { jsPDF } from "jspdf"

const TYPES = {
  "a4": [595, 842]
}

const _createCanvas = async function (el, noClass) {
  return html2canvas(el, {
      backgroundColor: '#ffffff',
      allowTaint: false,
      useCORS: true,
      ignoreElements: (element) => {
          for (let i = 0, len = noClass.length; i < len; ++i) {
              if ([].includes.call(element.classList, noClass[i])) {
                  return true;
              }
          }
      }
  })
}

class Html2Pdf {
  constructor(option) {
    this.title = "";                // 文件标题
    this.noClass = ["no2canvas"];   // 需要忽略的class名
    this.type = "a4";               // 生成类型默认为A4纸张
    this.el;                        // 生成的目标元素
    this.beforeFn;                  // 生成图像前可执行
    this.afterFn;                   // 生成图像后可执行
    Object.assign(this, option);
    return this;
  }
  async start() {
    const { title, type, el, beforeFn, afterFn, noClass } = this;
    const [w, h] = TYPES[type];
    if (!el) throw new Error("Missing target element!")
    beforeFn && await beforeFn.call(this);
    const canvas = await _createCanvas(el, noClass);
    let dataURL = await canvas.toDataURL('image/jpeg', 1.0);
    afterFn && await afterFn.call(this);
    // 生成PDF
    const { width, height } = canvas
    let pageHeight = width / w * h;
    let leftHeight = height;
    let position = 0;
    let imgHeight = w / width * height;
    let PDF = new jsPDF('', 'pt', type);
    if (leftHeight < pageHeight) {
      PDF.addImage(dataURL, 'JPEG', 0, 0, w, imgHeight)
    } else {
      while (leftHeight > 0) {
        PDF.addImage(dataURL, 'JPEG', 0, position, w, imgHeight);
        leftHeight -= pageHeight;
        position -= h;
        if (leftHeight > 0) PDF.addPage()
      }
    }
    PDF.save(title + '.pdf')
  }
}

export default Html2Pdf
